import Vue from 'vue'
import Vuex from 'vuex'
import { getSession, setSession } from '@/utils/session'
import { sysQueryNoticeByOneSelf } from '@/api/admin/system/sysNotice.js'
Vue.use(Vuex)

const state = {
  userInfo: JSON.parse(getSession('userinfo')) || null,
  messageTotal: 0,
  userEditData: {},
}

const getters = {
  userId(state) {
    if (!state.userInfo) return
    return state.userInfo.id
  },
  userType(state) {
    if (!state.userInfo) return
    return state.userInfo.type
  },
  account(state) {
    if (!state.userInfo) return
    return state.userInfo.account
  },
  username(state) {
    if (!state.userInfo) return
    return state.userInfo.userName
  },
  level(state) {
    if (!state.userInfo) return
    return state.userInfo.level
  },
  deptId(state) {
    if (!state.userInfo && !state.userInfo.deptId) return
    return state.userInfo.deptId
  },
  deptFullData(state) {
    if (!state.userInfo && !state.userInfo.deptFullData) return
    return state.userInfo.deptFullData
  },
  schoolDeptId(state) {
    if (
      state &&
      state.userInfo.deptFullData.childList &&
      state.userInfo.deptFullData.childList.length
    ) {
      return state.userInfo.deptFullData.childList[0].id
    } else {
      return false
    }
  },
  userData(state) {
    if (!state.userInfo) return
    return state.userInfo
  },
  userPture(state) {
    if (!state.userInfo) return
    if (state.userInfo.attachmentId != '-1') {
      return state.userInfo.sysAttachment.httpUrl
    } else {
      return undefined
    }
  },
  msgTotal(state) {
    if (!state.messageTotal) return
    return state.messageTotal
  },
  userEditData(state) {
    if (!state.userEditData) return
    return state.userEditData
  },
}

const actions = {
  setUserInfo({ commit }, obj) {
    let userinfo = obj ? obj : JSON.parse(getSession('userinfo'))
    commit('SETUSERINFO', userinfo)
  },
  getMessageInfo({ commit }) {
    let listQuery = {
      page: 1,
      limit: 10,
      type: 2,
    }
    sysQueryNoticeByOneSelf(listQuery).then((res) => {
      commit('GETMESSAGEINFO', res.data.count)
    })
  },
  setUserEditData({ commit }) {
    commit('USEREDITDATA', commit)
  },
}

const mutations = {
  SETUSERINFO: (state, d) => {
    setSession('userinfo', JSON.stringify(d))
    state.userInfo = d
  },
  GETMESSAGEINFO: (state, d) => {
    state.messageTotal = d
  },
  USEREDITDATA: (state, d) => {
    state.userEditData = d
  },
}

export default {
  state,
  getters,
  actions,
  mutations,
}
